#include<iostream>
#include<cstring>
#include<vector>
#include<queue>

using namespace std;

typedef pair<int,int> p;

const int N = 1000000 + 10;

int h[N],w[N],e[N],ne[N],idx;
int dis[N];
int n,m;
int st[N];


void add(int a, int b, int c)
{
	e[idx]=b,w[idx]=c,ne[idx]=h[a],h[a]=idx++;
}

int dijkstra()
{
	priority_queue<p, vector<p>, greater<p>> heap;
	memset(dis, 0x3f, sizeof dis);
	dis[1] = 0;
	heap.push({0,1});
	while(heap.size())
	{
		auto t = heap.top();
		heap.pop();
		
		int distance = t.first;
		int ver = t.second;
		
		if(st[ver]) continue;
		st[ver] = 1;
		
		for(int i=h[ver]; i != -1; i=ne[i])
		{
			int j = e[i];
			if(dis[j] > dis[ver] + w[i])
			{
				dis[j] = dis[ver] + w[i];
				heap.push({dis[j],j});
			}
		}
	}
	return dis[n];
}





int main()
{
	
	cin>>n>>m;
	memset(h,-1,sizeof h);
	for(int i=0; i<m; i++)
	{
		int a,b;
		scanf("%d%d",&a,&b);
		add(a,b,1);
		add(b,a,1);		
	}
	cout<<dijkstra()-1;	
	return 0;
}
